import axios from 'axios'
import {
  MessageBox,
  Message,
  Loading
} from 'element-ui'
import store from '@/store'
import {
  getToken
} from '@/utils/auth'
import {
  getWarehouse
} from '@/utils/warehouseAuth'

let loading

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    // const token = store.getters.token
    const token = getToken()
    if (token) {
      config.headers['Authorization'] = token
    }

    const warehouse = getWarehouse()
    if (warehouse) {
      config.headers['Warehouse'] = warehouse
    }

    loading = Loading.service({
      lock: true,
      text: '正在请求',
      background: 'rgba(0, 0, 0, 0)'
    })

    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    // 响应成功，关闭蒙层
    loading.close()
    const res = response.data

    if (res.code !== 1) {
      if (res.subCode === 'unauthorized') {
        // to re-login
        MessageBox.confirm('登录已失效', '离开确认', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      } else if (res.subCode === 'question') {
        return res
      } else {
        Message({
          message: res.msg || 'Error',
          type: 'error',
          duration: 5 * 1000
        })
      }
      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      return res
    }
  },
  error => {
    // 响应失败，关闭蒙层
    loading.close()
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
